package com.bignerdranch.android.criminalintent;

import java.util.ArrayList;
import java.util.UUID;

import android.content.Context;
import android.util.Log;

public class CrimeLab {
	
	private ArrayList<Crime> mCrimes;	
	private static CrimeLab sCrimeLab;
	private static final String TAG = "CrimeLab";
	private static final String FILE_NAME = "crimes.json";
	private CriminalIntentJsonSerializer mSer;
//	private Context mAppcontext;
	
	private CrimeLab(Context appContext){
//		mAppcontext = appContext;
		mSer = new CriminalIntentJsonSerializer(appContext, FILE_NAME);
		try{
			mCrimes = mSer.loadCrimes();
		}catch(Exception e){
			mCrimes = new ArrayList<Crime>();
			Log.e(TAG, "Error while loading crimes", e);
		}
	}
	
	public void addCrime(Crime c){
		mCrimes.add(c);
	}
	
	public static CrimeLab get(Context c){
		if(sCrimeLab == null){
			sCrimeLab = new CrimeLab(c);
		}
		return sCrimeLab;
	}
	
	public ArrayList<Crime> getCrimes(){
		return mCrimes;
	}
	
	public Crime getCrime(UUID id){
		for (Crime c : mCrimes) {
			if(c.getId().equals(id)){
				return c;
			}
		}
		return null;
	}
	
	public boolean saveCrimes(){
		try{
			mSer.saveCrimes(mCrimes);
			Log.d(TAG, "crimes saved to file");
			return true;
		}catch(Exception e){
			Log.e(TAG, "Error saving crime", e);
			return false;
		}
	}
	
	public void deleteCrime(Crime c){
		mCrimes.remove(c);
	}
}
	